import { GET_PNG_HREF } from '@conf';
import './index.less';
import { useMemo, useState } from 'react';

export default ({
	mahjong,
	changeMargin,
	size,
}: {
	mahjong: {
		id: number;
		right: Boolean;
		active?: Boolean;
	};
	changeMargin?: Function;
	size?: Number;
}) => {
	const ACTIVE_TRANS_Y = '-30%'; // px
	const CLICK_VERIFY_DISTANCE = 10; // px
	const CLICK_VERIFY_TIME = 300; // ms
	const DURATION_TIME = 0.3; // s
	const [data, setdata] = useState({
		is_moving: false,
		trans_x: 0,
		trans_y: 0,
	});
	const tansinfo = useMemo(() => {
		const { is_moving, trans_x: x, trans_y: y } = data;
		const duration = is_moving ? 0 : DURATION_TIME;
		return { x, y, duration };
	}, [data]);

	let is_click = true;
	let timeout = null;
	function onMouseDown({
		clientX: startx,
		clientY: starty,
		buttons,
	}: {
		clientX: any;
		clientY: number;
		buttons: number;
	}) {
		if (buttons == 2) return;
		is_click = true;
		timeout = setTimeout(() => {
			is_click = false;
		}, CLICK_VERIFY_TIME);
		document.onmousemove = ({ clientX, clientY }) => {
			const trans_x = clientX - startx;
			const trans_y = clientY - starty;
			setdata({ trans_x, trans_y, is_moving: true });
			if (is_click && (trans_x > CLICK_VERIFY_DISTANCE || trans_y > CLICK_VERIFY_DISTANCE)) is_click = false;
		};
		document.onmouseup = () => {
			if (is_click) mahjong.active = !mahjong.active;
			setdata({ is_moving: false, trans_x: 0, trans_y: 0 });
			document.onmousemove = null;
		};
	}

	// if (mahjong && mahjong.id > 0)
	if (!mahjong || mahjong.id === undefined) return null;
	switch (mahjong.id) {
		case 0:
			return <p className=' my-6 '></p>;
		case -1:
			return <p className=' mr-3'></p>;
		default:
			return (
				<img
					className={` cur select-none inline-block relative h-20 ${mahjong.right ? 'mr-5' : 'mr-0'} `}
					style={{
						transform: `translate(${tansinfo.x}px, ${
							tansinfo.y ? tansinfo.y + 'px' : mahjong.active ? ACTIVE_TRANS_Y : '0%'
						})`,
						transition: `all ${tansinfo.duration}s`,
						zIndex: `${data.is_moving ? 999 : 1}`,
					}}
					draggable='false'
					src={GET_PNG_HREF(mahjong.id)}
					onContextMenu={(e) => {
						e.preventDefault();
						changeMargin && changeMargin('right');
					}}
					onMouseDown={onMouseDown}
				/>
			);
	}
};
